package com.fled.itsmbigscreen.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fled.itsmbigscreen.dto.HuorongResponseDto;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.Base64;
import java.util.Formatter;
import java.util.stream.Collectors;

@Component
public class HuorongUtils {


    private static String secretId;

    @Value("${huorong.secretId}")
    public void setSecretId(String secretId) {
        HuorongUtils.secretId = secretId;
    }

    private static String secretKey;

    @Value("${huorong.secretKey}")
    public void setSecretKey(String secretKey) {
        HuorongUtils.secretKey = secretKey;
    }


    private static final String HMAC_SHA1 = "HmacSHA1";


    public static String createAuthorization(String method, String requestBody) throws NoSuchAlgorithmException, InvalidKeyException {
        String o = new String();
        try {
            long expires = System.currentTimeMillis() / 1000 + 604800; // 过期时间
            String apiEndpoint = method; // 替换成您的API端点

            // 构建完整的API URL
            String apiUrl = "http://172.16.1.200:8080" + apiEndpoint; // 替换成您的实际API URL

            // 创建URL对象
            URL url = new URL(apiUrl);

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod("POST");

            // 构建请求头
            String authorizationHeader = generateAuthorizationHeader(secretKey, secretId, expires, requestBody, method);
            connection.setRequestProperty("Authorization", authorizationHeader);
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");

            // 启用输入和输出流
            connection.setDoOutput(true);

            // 设置请求体
            if (!StringUtils.isEmpty(requestBody)) {
                try (OutputStream os = connection.getOutputStream()) {
                    byte[] input = requestBody.getBytes(StandardCharsets.UTF_8);
                    os.write(input, 0, input.length);
                }
            }


            // 获取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取响应内容
                try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                    String response = br.lines().collect(Collectors.joining("\n"));
                    HuorongResponseDto huorongResponseDto = JSONObject.parseObject(response, HuorongResponseDto.class);
                    Object data = huorongResponseDto.getData();
                    if (data != null) {
                        o = JSON.toJSONString(data);
                    }
                }
            } else {
                // 处理错误响应
                System.err.println("HTTP error code: " + responseCode);
            }

            // 关闭连接
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return o;
    }


    private static String generateAuthorizationHeader(String secretKey, String secretId, long expires, String requestBody, String method) throws Exception {
        // 计算请求体的MD5
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        if (StringUtils.isEmpty(requestBody)) {
            requestBody = "";
        }
        byte[] md5Bytes = md5.digest(requestBody.getBytes(StandardCharsets.UTF_8));
        String contentMD5 = Base64.getEncoder().encodeToString(md5Bytes);

        // 构建规范化资源
        if (method.charAt(0) == '/') {
            method = method.substring(1);
        }
        String canonicalizedResource = method; // 替换成您的API端点


        // 构建待签名字符串
        String stringToSign = secretId + "\n" + expires + "\nPOST\n" + contentMD5 + "\n" + canonicalizedResource;
//        String stringToSign = secretId  + expires + "POST" + contentMD5 + canonicalizedResource;
//        byte[] bytes = calculateRFC2104HMAC(
//        String stringToSign =   secretId + "\n"
//                        + expires + "\n"
//                        + HttpMethod.POST.toString() + "\n"
//                        + contentMD5 + "\n"
//                        + canonicalizedResource;
        String Signature = calculateRFC2104HMAC(stringToSign, secretKey);
//        String  Signature = Base64.getEncoder().encodeToString(bytes);

        // 计算签名
//        byte[] keyBytes = secretKey.getBytes(StandardCharsets.UTF_8);
//        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "HmacSHA1");
//        Mac mac = Mac.getInstance("HmacSHA1");
//        mac.init(keySpec);
//        byte[] hmacBytes = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));

//        String sign = Base64.getEncoder().encodeToString( calculateRFC2104HMAC(stringToSign,secretKey));

        // 构建Authorization头
        String authInfo = "HRESS" + secretId + ":" + expires + ":" + Signature;
        return authInfo;
    }


    private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";

    private static String toHexString(byte[] bytes) {
        Formatter formatter = new Formatter();
        for (byte b : bytes) {
            formatter.format("%02x", b);
        }
        return formatter.toString();
    }


    public static String calculateRFC2104HMAC(String data, String key) throws SignatureException, NoSuchAlgorithmException, InvalidKeyException {
        String secretKey = key;
        String message = data;

        // 创建HmacSHA1实例
        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA1");
        mac.init(secretKeySpec);

        // 计算HmacSHA1
        byte[] hmacBytes = mac.doFinal(message.getBytes(StandardCharsets.UTF_8));

        // 将结果转换为Base64编码
        String hmacBase64 = Base64.getEncoder().encodeToString(hmacBytes);
        return hmacBase64;
    }

}
